var QWE = "!QWKILFUCKE!";
var isIE = navigator.userAgent.indexOf("MSIE") >= 0;
var g_JustSubmitedData;
var g_selectedId = new Array();
var g_TABLE_RESULT_HEAD_IDX = 0;
String.prototype.replaceAll = function(s1, s2) {
	return this.replace(new RegExp(s1, "gm"), s2);
};
String.prototype.endsWith = function(suffix) {
	return this.indexOf(suffix, this.length - suffix.length) != -1;
};
//初始化输入法
function initInputMethods() {
	//外键字段输入法：
	replaceImportedKeyInputs();
	//缓冲输入：
	//initInputCahces();
	//initSelectCahces();
	//initSpanCahces();
}

function getParameters() {

	var args = new Object();
	var query = location.search.substring(1); // Get query string
	var pairs = query.split("&"); // Break at ampersand
	var len121 = pairs.length;
	for ( var i = 0; i < len121; i++) {
		var pos = pairs[i].indexOf('='); // Look for "name=value"
		if (pos == -1)
			continue; // If not found, skip
		var argname = pairs[i].substring(0, pos); // Extract the name
		var value = pairs[i].substring(pos + 1); // Extract the value
		value = decodeURIComponent(value); // Decode it, if needed
		args[argname] = value; // Store as a property
	}

	return args; // Return the object
}

function getParameter(name) {
	name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
	var regexS = "[\\?&]" + name + "=([^&#]*)";
	var regex = new RegExp(regexS);
	var results = regex.exec(window.location.href);
	if (results == null) {
		return null;
	} else {
		if (results.length) {
			if (results.length > 1) {
				var value = decodeURIComponent(results[1]);
				return value;
			}
		}

	}
	
	return null;
}

function copyUrl2Form() {
	var parameters = getParameters();
	for ( var name in parameters) {
		var element = document.getElementById(name);
		if (element) {
			element.value = parameters[name];
		}
	}
}


function callReturn(id,code,name){
	    var opennerWnd=window.dialogArguments;
		var idInput2Return=opennerWnd.document.getElementById(getParameter("idInput2Return"));
		if(idInput2Return){
			idInput2Return.value=id;
		}
		var nameInput2Return=opennerWnd.document.getElementById(getParameter("nameInput2Return"));
		if(nameInput2Return){
			
			nameInput2Return.value=code+"-"+name;
		}
		var olds=getCookie("last_"+getTablevarName());
		if(olds!=null&&olds.length>300){
			olds=olds.substring(olds.length-300);
		}
		if(olds==null||olds==""){
			olds=",";
		}
		if(olds.indexOf(id)==-1){
			setCookie("last_"+getTablevarName(),olds+id+",");
		}
		
		
}
function copyUrl2FormSetDisabled() {
	var parameters = getParameters();
	for ( var name in parameters) {
		var element = document.getElementById(name);
		if (element) {
			element.value = parameters[name];
			if (element.value != '' && element.value != null) {
				element.disabled = true;
			}
		}
	}
}
function replaceImportedKeyInputs() {

	var inputs1 = document.getElementsByTagName("input");
	var inputs = copyOf(inputs1);
	var len321 = inputs.length;
	for ( var i = 0; i < len321; i++) {
		var ip = inputs[i];
		//ip.setAttribute("parentTable","smgCenterInfo");//TODO
		if (ip.getAttribute("parentTable") && ip.getAttribute("parentTable") != "") {
			replaceImportedKeyInput(ip);
		} else {
			ip.ondblclick = function() {
				selectRecent(this);
			};
		}
	}
}

function getParentTR(ee) {
	if (ee.tagName == "tr" || ee.tagName == "TR") {
		return ee;
	}
	if (ee.parentNode != null && ee.parentNode != ee) {
		return getParentTR(ee.parentNode);
	}
	return null;
}
function getTROfInput(ip) {
	var tr = getParentTR(ip.parentNode);
	if (tr && ip.getAttribute("parentTable") && ip.getAttribute("parentTable") != "") {
		var ptr = getParentTR(tr.parentNode);
		if (ptr) {
			tr = ptr;
		}
	}
	return tr;
}
function getTablevarName() {
	var url = window.location.href;
	var idx1 = url.indexOf("table");
	url = url.substring(idx1 + 6);
	var idx2 = url.indexOf("/");
	url = url.substring(0, idx2);
	return url;
}
function getPreTDOfInput(obj,className){
	var td=getOwnTDOfInput(obj,className);
	if(td){
		var preTD=JBF.getPreElement(td);
		return preTD;
	}
	return td;
}
function getOwnTDOfInput(obj,className){
	var td=JBF.getParentNodeByClassName(className,obj);
	return td;
}

function initInputCahces() {
	var inputs = document.getElementsByTagName("input");
	var tn = getTablevarName();
	var len123 = inputs.length;
	for ( var i = 0; i < len123; i++) {
		var ip = inputs[i];
		if (getTROfInput(ip)) {
			if(ip.attributes["type"]&&ip.attributes["type"].nodeValue!="button"){

				if(!(ip.attributes["changeColor"]&&ip.attributes["changeColor"].nodeValue)){
					changeBgColor(ip);
				}
			}
		}
		var v = getParameter(ip.id);
		if (v) {
		} else {
			v = getParameter(tn + "." + ip.id);
		}
		if (v) {
			if (v != "" && v != "null") {
				ip.value = v;
			}
		}

	}
}

function initSpanCahces() {
	var spans = document.getElementsByTagName("span");
	var tn = getTablevarName();
	for ( var i = 0; i < spans.length; i++) {
		var ip = spans[i];
		if (getTROfInput(ip)) {
			if(!(ip.attributes["changeColor"]&&ip.attributes["changeColor"].nodeValue)){
				changeBgColor(ip);
			}
		}
		var v = getParameter(ip.id);
		if (v) {
		} else {
			v = getParameter(tn + "." + ip.id);
		}
		if (v) {
			if (v != "" && v != "null") {
				ip.value = v;
			}
		}

	}
}

function changeBgColor(obj){
	obj.onfocus = function() {	
		var preTd = getPreTDOfInput(this,"showValue");
		var ownTd=getOwnTDOfInput(this,"showValue");
		if(ownTd.firstChild.tagName == "SPAN"){
			ownTd.firstChild.style.border = "1px solid #ff0000";
		}
		preTd.setAttribute("class", "selectedInputTD");
		preTd.setAttribute("className", "selectedInputTD");					
		ownTd.setAttribute("class", "selectedInput");
		ownTd.setAttribute("className", "selectedInput");
	};
	obj.onblur = function() {
		var preTd = getPreTDOfInput(this,"selectedInput"); 
		var ownTd=getOwnTDOfInput(this,"selectedInput");
		if(ownTd.firstChild.tagName == "SPAN"){
			ownTd.firstChild.style.border = "1px solid #9cb3e2";
		}
		preTd.setAttribute("class", "showText");
		preTd.setAttribute("className", "showText");
		ownTd.setAttribute("class", "showValue");
		ownTd.setAttribute("className", "showValue");
	};
}
function initSelectCahces() {
	var inputs = document.getElementsByTagName("select");
	var tn = getTablevarName();
	var len123 = inputs.length;
	for ( var i = 0; i < len123; i++) {
		var ip = inputs[i];
		if (getTROfInput(ip)) {
			if(!(ip.attributes["changeColor"]&&ip.attributes["changeColor"].nodeValue)){
				changeBgColor(ip);
			}
		}
		var v = getParameter(ip.id);
		if (v) {
		} else {
			v = getParameter(tn + "." + ip.id);
		}
		if (v) {
			if (v != "" && v != "null") {
				ip.value = v;
			}
		}

	}
}

function setCookie(name, value)// 两个参数，一个是cookie的名子，一个是值
{
	var today = new Date();
	var expires_date = new Date(today.getTime() + (1000 * 60 * 60 * 24 * 10000));
	document.cookie = name + "=" + escape(value) + ";expires="
			+ expires_date.toGMTString();
}
function getCookie(name)// 读取cookies函数
{
	var arr = document.cookie
			.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)"));
	if (arr != null)
		return unescape(arr[2]);
	return null;

}
function browseEntity(browseEntityButton, myField, parentTable, parentTableTitle,
		justVisited) {
	//TODO
	var url=JBF.getUrl() +"pages/table/"+parentTable+"/" + parentTable
			+ "List.html?justVisited=" + justVisited
			+ "&forSelectOne=true&idInput2Return=" + myField
			+ "&nameInput2Return=" + myField.replace(".id", ".name");
	var returnValue = showModalDialog(url,window,"dialogWidth="+(screen.availWidth-80)+"px;dialogHeight="+(screen.availHeight-80)+"px;center:yes");

}
function onclickLi(li) {
	if (!li) {
		return;
	}
	if (li.tagName != "LI") {
		return;
	}
	var div = li.parentNode.parentNode;
	if (div.selectedId) {
		if (document.getElementById(div.selectedId)) {
			document.getElementById(div.selectedId).setAttribute("class", "");
			document.getElementById(div.selectedId).setAttribute("className",
					"");
		}

	}
	li.setAttribute("class", "liSelected");
	li.setAttribute("className", "liSelected");
	div.selectedId = li.getAttribute("id");
	div.selectedCode = li.getAttribute("code");
	div.selectedName = li.getAttribute("name");
	var ul = li.parentNode;
	var myField = ul.id;
	if (!myField) {
		myField = ul.getAttribute("id");
	}
	myField = myField.substring(3);
	document.getElementById(myField.replace(".id", ".name")).focus();
}
function nextLi(ul) {
	if (!ul) {
		return;
	}
	var div = ul.parentNode;
	var li0 = document.getElementById(div.selectedId);

	var li = null;
	if (li0) {
		li = JBF.getNextElement(li0);
	} else {
		li = ul.firstChild;
	}
	onclickLi(li);
}

function preLi(ul) {
	if (!ul) {
		return;
	}
	var div = ul.parentNode;
	var li0 = document.getElementById(div.selectedId);

	var li = null;
	if (li0) {
		li = li0.previousSibling;
	} else {
		li = ul.firstChild;
	}
	onclickLi(li);
}

function selectFirst(listDiv) {
	if (listDiv.firstChild) {
		var li = listDiv.firstChild.firstChild;
		onclickLi(li);
	}

}
function getListHTML(inputValue, myField, parentTable, parentTableTitle, refField,
		refCodeField, refNameField) {//!query.do
	// TODO 使用缓存
	var url1 = parentTable+"!queryIdCodeNames.do";
	var data1 = "sg_myField=" + myField + "&sg_inputValue=" + inputValue;
	var responseText="";
	JBF.ajax(url1,data1,function(msg) {
		responseText=msg.sg_queryIdCodeNames;
	});
	return responseText;
}

function ondblclickLi(li) {
	var listDiv = li.parentNode.parentNode;
	var ul = li.parentNode;
	var myField = ul.id;
	if (!myField) {
		myField = ul.getAttribute("id");
	}
	myField = myField.substring(3);
	listDiv.style.display = "none";
	document.getElementById(myField).value = listDiv.selectedId;
	document.getElementById(myField.replace(".id",".name")).value = listDiv.selectedCode
			+ "-" + listDiv.selectedName;
}

function onkeyupEntity(e, codeNameInput, myField, parentTable, parentTableTitle,
		refField, refCodeField, refNameField) {
	document.getElementById(myField).value="";

	e = e || event;
	var currKey = e.keyCode || e.which || e.charCode;
	var listDiv = document.getElementById("list_" + myField);
	if (listDiv.style.display == "none") {
		listDiv.style.display = "";
		codeNameInput.focus();
	}
	if (currKey == 32) {// 回车13 -- 空格 32
		listDiv.style.display = "none";
		if (listDiv.selectedId) {
			document.getElementById(myField).value = listDiv.selectedId;
			codeNameInput.value = listDiv.selectedCode + "-"
					+ listDiv.selectedName;
//			var ni = getNextInput(codeNameInput);
//			if (ni) {
//				codeNameInput.blur();
//				ni.focus();
//			}
		}

	} else if (currKey == 38) {// 上箭头
		preLi(document.getElementById("UL_" + myField));
	} else if (currKey == 40) {// 下箭头
		nextLi(document.getElementById("UL_" + myField));
	} else if (currKey == 37) {// 左箭头

	} else if (currKey == 39) {// 右箭头

	} else {
		if (codeNameInput.value && codeNameInput.value != "") {
			var html = getListHTML(codeNameInput.value, myField, parentTable,
					parentTableTitle, refField, refCodeField, refNameField);
			listDiv.innerHTML = html;
			selectFirst(listDiv);
			codeNameInput.focus();
		}
		  else{
					listDiv.style.display="none";
					document.getElementById(myField).value="";
					
					// codeNameInput.blur();
					   
				}

	}
}
function dropEntity(dropEntityButton, myField, parentTable, parentTableTitle,
		refField, refCodeField, refNameField) {
	var listDiv = document.getElementById("list_" + myField);
	if (listDiv.style.display == "none") {
		var html = getListHTML(document.getElementById(myField.replace(".id",".name")).value,
				myField, parentTable, parentTableTitle, refField, refCodeField,
				refNameField);
		listDiv.innerHTML = html;
		listDiv.style.display = "";
		selectFirst(listDiv);
		document.getElementById(myField.replace(".id",".name")).focus();
	} else {
		listDiv.style.display = "none";
	}

}

function copyOf(aa) {
	if (aa) {
		var bb = new Array();
		for ( var i = 0; i < aa.length; i++) {
			bb[i] = aa[i];
		}
		return bb;
	} else {
		return aa;
	}

}
var g_pojoMap;
function replaceImportedKeyInput(ip) {
	var myField = ip.id;
	var parentTable = ip.getAttribute("parentTable");
	var parentTableTitle = ip.getAttribute("parentTableTitle");
	var parentOpObjName=ip.getAttribute("parentOpObjName");
	var changeColor=null!=ip.getAttribute("changeColor")?ip.getAttribute("changeColor"):"";
	var refField = "id";//ip.getAttribute("refField");
	var refCodeField = "code";//ip.getAttribute("refCodeField");
	var refNameField = "name";//ip.getAttribute("refNameField");
	var readonly = ip.getAttribute("readonly");
	var opWidth=ip.getAttribute("opWidth");
	//ip.type = "hidden";

	var codeNameDiv = document.createElement("div");
	if(ip.parentNode.insertAfter){
		ip.parentNode.insertAfter(codeNameDiv,ip);
	}else if(ip.parentNode.insertBefore){
		ip.parentNode.insertBefore(codeNameDiv,ip);
	}else{
		ip.parentNode.appendChild(codeNameDiv);
	}
	
	codeNameDiv.id = "codeNameDiv";
	codeNameDiv.setAttribute("id", "codeNameDiv");
	codeNameDiv.style.width=opWidth+"px";
	
	var html = "<table style='width:"+(opWidth)+"px;' class='codeNameTable'><tr>";
	var name =g_pojoMap?g_pojoMap[myField.replace(".id",".name")]:"";
	var imported=getParameter(myField.replace(".id",".name"));
	if(imported!=null&&imported!=""){
		name=imported;
	}
	
	var code =g_pojoMap?g_pojoMap[myField.replace(".id",".code")]:"";
	var imported=getParameter(myField.replace(".id",".code"));
	if(imported!=null&&imported!=""){
		code=imported;
	}
	var vvv="";
	if(!isNull(code)){
		vvv=code+"-" + name;
	}
	html += "<td><input onfocus='JBF.setFocusStyle(this);' onblur='JBF.setBlurStyle(this);' onkeydown='"+parentOpObjName+".checkKey(event);' style='width:"+(Number(opWidth)-50)+"px;' tabIndex='"+ip.tabIndex+"' type='text' value='"+vvv + "' id='" + myField.replace(".id",".name")
			+ "' name='" + myField.replace(".id",".name") + "' parentTable='" + parentTable 
			+"'changeColor='"+changeColor+"' onkeyup=\"onkeyupEntity(event,this,'" + myField + "','"
			+ parentTable + "','" + parentTableTitle + "','" + refField + "','"
			+ refCodeField + "','" + refNameField + "')\"></td>";
	if (readonly != "readonly") {
		html += "<td><div title='" + parentTableTitle
				+ "下拉列表' class='dropEntity' onclick=\"dropEntity(this,'"
				+ myField + "','" + parentTable + "','" + parentTableTitle + "','"
				+ refField + "','" + refCodeField + "','" + refNameField
				+ "')\">&nbsp;&nbsp;&nbsp;</div></td>";
		html += "<td><div title='" + parentTableTitle
				+ "浏览对话框' class='browseEntity' onclick=\"browseEntity(this,'"
				+ myField + "','" + parentTable + "','" + parentTableTitle
				+ "')\">&nbsp;&nbsp;&nbsp;</div></td>";
		html += "<td><div title='最近访问的"
				+ parentTableTitle
				+ "' class='browseEntityJustVisited' onclick=\"browseEntity(this,'"
				+ myField + "','" + parentTable + "','" + parentTableTitle
				+ "',true)\">&nbsp;&nbsp;&nbsp;</div></td>";
	}
	html += "</tr></table>";
	html += "<div class='listDiv' id='list_" + ip.id
			+ "' style='position:absolute;display:none;'></div>";
	codeNameDiv.innerHTML = html;
	 var nip=document.getElementById(myField.replace(".id",".name"));
		
		if(nip.attachEvent){
			nip.attachEvent("onblur",function(){
				hidden1222("list_"+ip.id,document.getElementById(ip.id.replace(".id",".name")),ip);
			});
		}else if(nip.addEventListener){
			nip.addEventListener("blur",function(){
				hidden1222("list_"+ip.id,document.getElementById(ip.id.replace(".id",".name")),ip);
			},false);
		}else{
			nip.onblur=function(){
				hidden1222("list_"+ip.id,document.getElementById(ip.id.replace(".id",".name")),ip);
			};
		}
		
		
	}
	function hidden1222(ipid,namee,ip){
		if(document.getElementById(ipid).style.display=="none"){
			return;
		}
		setTimeout(function(){
			var iii=document.getElementById(ipid);
			if(ip&&ip.value==""){
				if(namee){
					namee.value="";
				}
			}
			iii.style.display="none";
			
		},500);
		
	}


function loadJustVisited2Table() {
	var ids_dot = getCookie("last_" + getTablevarName());
	document.getElementById("ids_dot").value = ids_dot;

}

function selectRecent(input) {
	var fieldId = input.getAttribute("fieldId");

	var old = getCookie("rec_" + fieldId);
	if (old != null) {
		if (old != "") {
			var div = document.createElement("div");
			div.onclick = function(event) {
				var e = event || window.event || window.top.event;
				var event_element = e.target ? e.target : e.srcElement;
				if (event_element.innerText) {
					input.value = event_element.innerText;
				} else if (event_element.contentText) {
					input.value = event_element.contentText;
				} else if (event_element.textContent) {
					input.value = event_element.textContent;
				} else {
					input.value = event_element.innerHTML;
				}
				this.parentNode.removeChild(this);
			};
			div.onblur = function(event) {
				var e = event || window.event || window.top.event;
				if (e && e.explicitOriginalTarget) {
					input.value = e.explicitOriginalTarget.textContent;
				}
				this.parentNode.removeChild(this);
			};
			var posinput = absPos(input);
			var top = parseInt111(posinput.y) + parseInt111(input.offsetHeight);
			div.style.cssText = "border:solid 1px #990000;cursor:hand;display: block;position:absolute;background-color:#ccaa00;z-index:9999;max-height:200px;overflow:auto;left:"
					+ posinput.x
					+ "px;top:"
					+ top
					+ "px;width:"
					+ input.offsetWidth + "px;";

			var div2 = document.createElement("div");
			div.appendChild(div2);
			var olds = old.split(QWE);
			var len = olds.length;
			for ( var i = 0; i < len; i++) {
				var v = olds[i];

				if (v != null && v != "null" && v != "") {
					var c = document.createElement("div");
					if (i % 2 == 0) {
						c.style.cssText = "padding:3px;background-color:#cc8800;";
					} else {
						c.style.cssText = "padding:3px;background-color:#eedd00;";

					}
					c.appendChild(document.createTextNode(v));
					div2.appendChild(c);

				}
			}
			window.document.body.appendChild(div);
			if (top + parseInt111(div.offsetHeight) > parseInt111(window.document.body.clientHeight)) {
				div.style.top = top
						- ((parseInt111(div.offsetHeight) + parseInt111(input.offsetHeight)))
						+ "px";
			}
			div.focus();

		}
	}
}
function saveCache4Field(input) {
	var inputs;
	if (input) {
		inputs = new Array();
		inputs[0] = input;
	} else {
		inputs = document.getElementsByTagName("input");
	}

	var len = inputs.length;
	for ( var i = 0; i < len; i++) {
		var input = inputs[i];
		if (input.value == null || input.value == "") {
			continue;
		}
		var fieldId = input.getAttribute("fieldId");
		if (fieldId) {
			if (fieldId != "") {
				var old = getCookie("rec_" + fieldId);
				if (old == null) {
					old = QWE;
				}
				var os = old.split(QWE);
				if (os.length) {
					if (os.length > 20) {
						old = QWE;
						for ( var j = os.length - 20; j < os.length; j++) {
							if (os[j]) {
								if (os[j] != "") {
									old += os[j] + QWE;
								}

							}
						}
					}
				}
				if (old.indexOf(QWE + input.value + QWE) == -1) {
					old += input.value + QWE;
					setCookie("rec_" + fieldId, old);
				}
			}
		}
	}
}
function isNull(s) {
	if (s) {
		if (s != "" && s != "null" && s != "undefined") {
			return false;
		}
	}
	return true;
}
